package com.itheima.algorithm.heap;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author: TylerZhong
 * @description:
 */
public class E04Leetcode295_2 {
    // 大顶堆
    private PriorityQueue<Integer> left = new PriorityQueue<>((a,b)-> Integer.compare(b,a));
    // 小顶堆
    private PriorityQueue<Integer> right = new PriorityQueue<>();

    public double findMedia() {
        if (left.size() == right.size()) {
            return (left.peek() + right.peek()) / 2.0;
        } else {
            return left.peek();
        }
    }

    public void addNum(int offered) {
        if (left.size() == right.size()) {
            right.offer(offered);
            left.offer(right.poll());
        } else {
            left.offer(offered);
            right.offer(left.poll());
        }
    }

    public static void main(String[] args) {
        // 以上浮为例，大概的实现逻辑
        Comparator<Integer> cmp = (a, b) -> Integer.compare(a, b); // 小顶堆比较器 compare -1 a<b, 0 a==b, 1 a>b
//        Comparator<Integer> cmp = (a, b) -> Integer.compare(b, a); // 大顶堆比较器 compare -1 b<a, 0 b==a, 1 b>a
        int a = 10; // 父元素值
        int b = 5; // 新增元素值
//        int b = 20;
        if (cmp.compare(a, b) > 0) {
            System.out.println("上浮");
        } else {
            System.out.println("停止上浮");
        }
    }

    public void test1() {
        E04Leetcode295_2 test = new E04Leetcode295_2();
        test.addNum(1);
        test.addNum(2);
        test.addNum(3);
        test.addNum(7);
        test.addNum(8);
        test.addNum(9);
        System.out.println(test);
        System.out.println(test.findMedia());
        test.addNum(10);
        System.out.println(test);
        System.out.println(test.findMedia());
        test.addNum(4);
        System.out.println(test);
        System.out.println(test.findMedia());
    }
}
